package com.newidea.jiangong.service.impi;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newidea.jiangong.component.HeatComponent;
import com.newidea.jiangong.entity.MachineMonitor;
import com.newidea.jiangong.mapper.MachineMonitorMapper;
import com.newidea.jiangong.service.MachineMonitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


@Service
@Slf4j
public class MachineMonitorServiceImpl extends ServiceImpl<MachineMonitorMapper, MachineMonitor>
    implements MachineMonitorService {

    /**
     * 采集机房监控的地址
     */
    @Value("${collect.url.machineMonitor}")
    private String machineMonitorUrl;

    private final HeatComponent heatComponent;

    public MachineMonitorServiceImpl(HeatComponent heatComponent) {this.heatComponent = heatComponent;}


    /**
     * 采集机房监控数据
     *
     * @param company 所属公司
     * @param token   token
     */
    @Override
    public void collect(String company, String token) {
        final String paramStr = "{\"departmentId\":\"1717469205139427328\"," +
            "\"viewColumnNamesOne\":[\"column1\",\"column2\",\"oneTemBad\",\"column3\",\"column4\"," +
            "\"oneStressBad\"],\"viewColumnNamesTwo\":[\"column1\",\"column2\",\"twoTemBad\",\"column3\"," +
            "\"column4\",\"twoStressBad\"],\"pageNum\":1,\"pageSize\":200}";
        // 请求参数
        JSONObject param = JSONUtil.parseObj(paramStr);

        // 获取要采集的根部门id
        JSONArray rootDepartments = heatComponent.getRootDepartments(token);

        String now = DateUtil.now();
        // 采集数量
        AtomicInteger quantity = new AtomicInteger(0);
        for (int i = 0; i < rootDepartments.size(); i++) {
            // 以前数据设置为旧数据
            MachineMonitor updateEntity = new MachineMonitor();
            updateEntity.setNewest(false);
            QueryWrapper<MachineMonitor> updateWrapper = new QueryWrapper<>();
            // 是否获取最新的数据
            updateWrapper.eq("company", company);
            this.update(updateEntity, updateWrapper);

            //  参数设置部门id
            JSONObject rootDepartment = rootDepartments.getJSONObject(i);
            String departmentId = rootDepartment.getStr("departmentId");
            param.set("departmentId", departmentId);

            insertPagingData(param, token, quantity, now, company);
        }
        log.info(company + "： 采集机房监控数据：{}条。", quantity.get());
    }

    /**
     * 新增机房监控数据，包括分页数据
     *
     * @param param    请求参数
     * @param token    token
     * @param quantity 采集数量
     * @param now      采集时间
     * @param company  所属公司
     */
    private void insertPagingData(
        JSONObject param, String token, AtomicInteger quantity, String now, String company
    ) {
        // 获取机房监控数据
        JSONObject data = heatComponent.httpPost(param, machineMonitorUrl, token);
        // 获取采集数据
        JSONArray list = data.getJSONArray("list");
        // 插入获取的当前页数据
        insertPageData(list, now, company);
        // 累加采集数量
        quantity.addAndGet(list.size());
        // 是否有下一页
        if (data.getBool("hasNextPage")) {
            // 获取下一页数据
            param.set("pageNum", param.getInt("pageNum") + 1);
            insertPagingData(param, token, quantity, now, company);
        }
    }

    /**
     * 插入获取的当前页数据
     *
     * @param list    当前页数据
     * @param now     采集时间
     * @param company 所属公司
     */
    private void insertPageData(JSONArray list, String now, String company) {
        if (CollUtil.isNotEmpty(list)) {
            List<MachineMonitor> machineMonitors = new ArrayList<>();
            for (int x = 0; x < list.size(); x++) {
                // 从json数据中获取机房监控数据
                JSONObject jsonObject = list.getJSONObject(x);
                MachineMonitor machineMonitor = new MachineMonitor();
                machineMonitor.setProjectId(jsonObject.getStr("projectId"));
                machineMonitor.setProjectName(jsonObject.getStr("projectName"));
                machineMonitor.setDeviceName(jsonObject.getStr("deviceName"));
                machineMonitor.setDt(jsonObject.getStr("dt"));
                // 一次相关数据
                JSONObject oneJson = jsonObject.getJSONObject("realDataYcjcView");
                if (oneJson != null) {
                    machineMonitor.setOneColumn1(oneJson.getStr("column1"));
                    machineMonitor.setOneColumn2(oneJson.getStr("column2"));
                    machineMonitor.setOneColumn3(oneJson.getStr("column3"));
                    machineMonitor.setOneColumn4(oneJson.getStr("column4"));
                    machineMonitor.setOneTemBad(oneJson.getStr("oneTemBad"));
                    machineMonitor.setOneStressBad(oneJson.getStr("oneStressBad"));
                }
                // 二次相关数据
                machineMonitor.setTwoColumn1(jsonObject.getStr("column1"));
                machineMonitor.setTwoColumn2(jsonObject.getStr("column2"));
                machineMonitor.setTwoColumn3(jsonObject.getStr("column3"));
                machineMonitor.setTwoColumn4(jsonObject.getStr("column4"));
                machineMonitor.setTwoTemBad(jsonObject.getStr("twoTemBad"));
                machineMonitor.setTwoStressBad(jsonObject.getStr("twoStressBad"));
                // 供热面积，暂时没有
                machineMonitor.setSupplyHeatArea(jsonObject.getStr("supplyHeatArea"));

                machineMonitor.setCompany(company);
                machineMonitor.setCreateTime(now);
                machineMonitor.setNewest(true);
                machineMonitors.add(machineMonitor);
            }
            this.saveBatch(machineMonitors);
        }
    }
}
